# coding=utf-8

import json
import logging

import time

import sys
from django.db import connection, transaction
from django.db import transaction
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.csrf import csrf_exempt, csrf_protect

from worldcup.apps.userModel.models import Travel, User, TravelEvent, TravelSearchLog
from worldcup.commons.CommonResult import rest, CommonResult
from worldcup.commons.SqlExecutor import executeQuery

logger = logging.getLogger('django')
reload(sys)
sys.setdefaultencoding('utf-8')


@rest
def is_have_travel(request):
	openid = request.GET["openid"]
	num = Travel.objects.filter(openid=openid).count()
	return CommonResult(0, num > 0)


@transaction.atomic
@rest
def create_travel(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	# 用户信息
	openid = reqest_params["openid"]
	if openid is None or openid == '':
		return CommonResult(-1, "openid不能为空")
	name = reqest_params["name"]
	if name is None or name == '':
		return CommonResult(-1, "name不能为空")
	wxid = reqest_params["wxid"]
	if wxid is None or wxid == '':
		return CommonResult(-1, "wxid不能为空")
	wxid = reqest_params["wxid"]
	gender = reqest_params["gender"]
	if gender is None or gender == '':
		return CommonResult(-1, "gender不能为空")
	age = reqest_params["age"]
	birth_year = reqest_params["birthYear"]

	peer_num = reqest_params["peerNum"]
	if peer_num is None or peer_num == '':
		return CommonResult(-1, "peer_num不能为空")
	support_teams = reqest_params["supportTeams"]
	labels = reqest_params["labels"]
	description = reqest_params["description"]

	# 出入境信息

	from_city = reqest_params["fromCity"]
	if from_city is None or from_city == '':
		return CommonResult(-1, "from_city不能为空")
	to_city = reqest_params["toCity"]
	if to_city is None or to_city == '':
		return CommonResult(-1, "to_city不能为空")
	start_date = reqest_params["startDate"]
	if start_date is None or start_date == '':
		return CommonResult(-1, "start_date不能为空")
	return_date = reqest_params["returnDate"]
	if return_date is None or return_date == '':
		return CommonResult(-1, "return_date不能为空")
	matches = reqest_params["matches"]
	matches = map(str, matches)
	vehicle = reqest_params["vehicle"]
	if vehicle is None or vehicle == '':
		return CommonResult(-1, "vehicle不能为空")
	vehicle_no = reqest_params["vehicleNo"]

	# 更新user表
	user = User.objects.filter(openid=openid).get()
	user.name = name
	user.wxid = wxid
	user.gender = gender
	user.age = age
	user.birth_year = birth_year
	user.support_teams = ",".join(support_teams)
	user.labels = ",".join(labels)
	user.description = description
	user.save()
	# 插入travel表
	main_travel = Travel(openid=openid, peer_num=peer_num, from_city=from_city, to_city=to_city,
						 matches=",".join(matches), start_date=start_date, end_date=return_date, vehicle=vehicle,
						 vehicle_no=vehicle_no, travel_type=1, created_at=int(time.time()))
	main_travel.save()
	# 旅程信息
	travels = reqest_params["travels"]
	for travel in travels:
		city = travel["city"]
		start_date = travel["startDate"]
		end_date = travel["endDate"]
		vehicle = travel["vehicle"]
		try:
			vehicle_no = travel["vehicleNo"]
		except 	KeyError:
			vehicle_no = None
		try:
			hotel = travel["hotel"]
		except KeyError:
			hotel = None
		try:
			hotel_name = travel["hotelName"]
		except KeyError:
			hotel_name = None
		detail_travel = Travel(openid=openid, peer_num=peer_num, to_city=city, start_date=start_date,
							 end_date=end_date, vehicle=vehicle, vehicle_no=vehicle_no,
							    hotel=hotel, hotel_name=hotel_name, travel_type=2, created_at=int(time.time()))
		detail_travel.save()
	return CommonResult(0, "success")


@transaction.atomic
@rest
def update_travel(request):
	try:
		reqest_params = json.loads(request.body)
	except ValueError:
		return CommonResult(-1, "数据格式错误")
	# 用户信息
	openid = reqest_params["openid"]
	if openid is None or openid == '':
		return CommonResult(-1, "openid不能为空")
	name = reqest_params["name"]
	if name is None or name == '':
		return CommonResult(-1, "name不能为空")
	wxid = reqest_params["wxid"]
	if wxid is None or wxid == '':
		return CommonResult(-1, "wxid不能为空")
	wxid = reqest_params["wxid"]
	gender = reqest_params["gender"]
	if gender is None or gender == '':
		return CommonResult(-1, "gender不能为空")
	age = reqest_params["age"]
	birth_year = reqest_params["birthYear"]
	peer_num = reqest_params["peerNum"]
	if peer_num is None or peer_num == '':
		return CommonResult(-1, "peer_num不能为空")
	support_teams = reqest_params["supportTeams"]
	labels = reqest_params["labels"]
	description = reqest_params["description"]

	# 出入境信息

	from_city = reqest_params["fromCity"]
	if from_city is None or from_city == '':
		return CommonResult(-1, "from_city不能为空")
	to_city = reqest_params["toCity"]
	if to_city is None or to_city == '':
		return CommonResult(-1, "to_city不能为空")
	start_date = reqest_params["startDate"]
	if start_date is None or start_date == '':
		return CommonResult(-1, "start_date不能为空")
	return_date = reqest_params["returnDate"]
	if return_date is None or return_date == '':
		return CommonResult(-1, "return_date不能为空")
	matches = reqest_params["matches"]
	matches = map(str, matches)
	vehicle = reqest_params["vehicle"]
	if vehicle is None or vehicle == '':
		return CommonResult(-1, "vehicle不能为空")
	vehicle_no = reqest_params["vehicleNo"]

	# 更新user表
	user = User.objects.filter(openid=openid).get()
	user.name = name
	user.wxid = wxid
	user.gender = gender
	user.age = age
	user.birth_year = birth_year
	user.support_teams = ",".join(support_teams)
	user.labels = ",".join(labels)
	user.description = description
	user.save()

	# 删除所有travel信息
	Travel.objects.filter(openid=openid).delete()
	# 出入境信息
	main_travel = Travel(openid=openid, peer_num=peer_num, from_city=from_city, to_city=to_city,
						 matches=",".join(matches), start_date=start_date, end_date=return_date, vehicle=vehicle,
						 vehicle_no=vehicle_no, travel_type=1,created_at=int(time.time()))
	main_travel.save()
	# 旅程信息
	travels = reqest_params["travels"]
	for travel in travels:
		city = travel["city"]
		start_date = travel["startDate"]
		end_date = travel["endDate"]
		vehicle = travel["vehicle"]
		try:
			vehicle_no = travel["vehicleNo"]
		except KeyError:
			vehicle_no = None
		try:
			hotel = travel["hotel"]
		except KeyError:
			hotel = None
		try:
			hotel_name = travel["hotelName"]
		except KeyError:
			hotel_name = None
		detail_travel = Travel(openid=openid, peer_num=peer_num, to_city=city, start_date=start_date,
							   end_date=end_date, vehicle=vehicle, vehicle_no=vehicle_no,
							   hotel=hotel, hotel_name=hotel_name, travel_type=2,created_at=int(time.time()))
		detail_travel.save()
	return CommonResult(0, "success")


@rest
def list_travel(request):
	cur_openid = request.GET.get("openid")		# 当前openid
	citys_str = request.GET.get("city")
	match = request.GET.get("match")
	date = request.GET.get("date")
	age_val = request.GET.get("age")
	gender_str = request.GET.get("gender")
	size = request.GET.get("size")
	page = request.GET.get("page")
	if citys_str is not None or match is not None or date is not None or age_val is not None or gender_str is not None:
		search_log = TravelSearchLog(openid = cur_openid, citys = citys_str,match=match,date = date, age = age_val, gender = gender_str)
		search_log.save()
	result = []

	sql = "select DISTINCT(a.openid),b.support_num as up_num "
	sql += " from userModel_travel a inner join userModel_user b on a.openid = b.openid "
	# sql += " left join userModel_travelmatching c on a.openid = c.ref_openid where c.openid = '" + cur_openid + "' "
	if citys_str is not None:
		citys = citys_str.split("|")
		citys_len = len(citys)
		index = 0
		for city in citys:
			if index == 0:
				sql += ' and( '
			else:
				sql += ' or '
			sql += ' (a.from_city like "%' + city.decode("utf-8") + '%" or a.to_city like "%' + city.decode(
				"utf-8") + '%") '
			if index == citys_len - 1:
				sql += ')'
			index += 1
	if gender_str is not None:
		genders = gender_str.split("|")
		if len(genders) == 1:
			sql += ' and b.gender = ' + genders[0]
		else:
			sql += ' and b.gender in (' + ",".join(genders) + " )"
	if date is not None:
		sql += " and a.start_date <= '" + date + "' and a.end_date >= '" + date + "' "
	if age_val is not None:
		if age_val == "1":
			age = "49-58"
		elif age_val == "2":
			age = "39-48"
		elif age_val == "3":
			age = "29-38"
		elif age_val == "4":
			age = "19-28"
		else:
			age = "0-18"
		ages = age.split("-")
		if len(ages) == 2:
			sql += " and b.age >= " + ages[0] + " and b.age <= " + ages[1] + " "
	if match is not None:
		sql += " and a.matches like '%" + match + "%'"
	# sql += " order by c.match_rate desc, openid"
	if size is not None and page is not None:
		sql += " limit " + str((int(page) - 1) * int(size)) + "," + size

	rows = executeQuery(sql)
	for row in rows:
		openid = row["openid"]
		# isApply 今天是否已经看过此人
		view_count = TravelEvent.objects.values("openid").filter(openid=cur_openid, rec_openid=openid, event=2, created_at__gte=int(time.mktime(
			time.strptime(time.strftime('%Y-%m-%d 00:00:00', time.localtime(time.time())), '%Y-%m-%d %H:%M:%S')))).distinct().count()
		is_apply = 1 if view_count > 0 else 0

		# isUp 今天是否点赞过此人
		up_count = TravelEvent.objects.values("openid").filter(openid=cur_openid, rec_openid=openid, event=1, created_at__gte=int(time.mktime(
			time.strptime(time.strftime('%Y-%m-%d 00:00:00', time.localtime(time.time())), '%Y-%m-%d %H:%M:%S')))).distinct().count()
		is_up = 1 if up_count > 0 else 0

		# isDate 是否约伴成功
		date_num = TravelEvent.objects.filter(openid=cur_openid, rec_openid=openid, event=3).count()
		if date_num == 0:
			date_num = TravelEvent.objects.filter(openid=openid, rec_openid=cur_openid, event=3).count()
		is_date = 1 if date_num > 0 else 0

		sql = "select a.openid,b.name,b.age,b.gender,b.support_teams,a.peer_num,a.matches," \
			  "a.from_city,a.to_city,a.start_date,a.end_date,b.description,b.support_num as up_num "
		sql += " from userModel_travel a inner join userModel_user b on a.openid = b.openid "
		sql += " where a.openid = '" + openid + "' and travel_type = 1"
		travels = executeQuery(sql)
		for travel in travels:
			if travel['up_num'] is None:
				travel['up_num'] = 0
			result.append({
				"openid": travel,
				"name": travel["name"],
				"age": travel["age"],
				"gender": travel["gender"],
				"supportTeams": [] if travel["support_teams"] is None or travel["support_teams"]=="" else travel["support_teams"].split(","),
				"peerNum": travel['peer_num'],
				"upNum": 0 if travel['up_num'] is None else travel['up_num'],
				"matches": [] if travel['matches'] is None or travel['matches'] == "" else travel['matches'].split(","),
				"fromCity": travel['from_city'],
				"toCity": travel['to_city'],
				"startDate": travel['start_date'],
				"returnDate": travel['end_date'],
				"description": travel['description'],
				"isApply": is_apply,
				"isUp": is_up,
				"isDate": is_date,
			})
	return CommonResult(0, result)


@rest
def get_travel(request):
	openid = request.GET["openid"]  # 被查看人
	record_openid = request.GET.get("recordOpenid")  # 查看人
	if record_openid is not None and openid != record_openid:
		# 记录查看关系
		travel_event = TravelEvent(openid=record_openid, rec_openid=openid, event=2, created_at=int(time.time()), status=1)
		travel_event.save()
		# 查询是否录入信息
		travel_num = Travel.objects.filter(openid=record_openid).count()
		if travel_num == 0:
			return CommonResult(-1, "您还没有录入行程信息!请点击右上角\"个人\"录入。")

		# isDate 是否约伴成功
		date_num = TravelEvent.objects.filter(openid=record_openid, rec_openid=openid, event=3).count()
		if date_num == 0:
			date_num = TravelEvent.objects.filter(openid=openid, rec_openid=record_openid, event=3).count()
		is_date = 1 if date_num > 0 else 0
	else:
		is_date = 0
	view_num = TravelEvent.objects.filter(rec_openid=openid, event=2).count()
	user = User.objects.filter(openid=openid).get()
	main_travel = Travel.objects.filter(openid=openid, travel_type=1).get()
	detail_travels = Travel.objects.filter(openid=openid, travel_type=2).all()
	detail_travel_results = []
	for detail_travel in detail_travels:
		detail_travel_results.append({
			"id": detail_travel.id,
			"city": detail_travel.to_city,
			"startDate": detail_travel.start_date,
			"endDate": detail_travel.end_date,
			"vehicle": detail_travel.vehicle,
			"vehicleNo": detail_travel.vehicle_no,
			"hotel": detail_travel.hotel,
			"hotelName": detail_travel.hotel_name
		})

	return {
		"openid": user.openid,
		"imgUrl": user.imgurl,
		"name": user.name,
		"wxid": user.wxid,
		"viewNum": view_num,
		"gender": user.gender,
		"birthYear": user.birth_year,
		"age": user.age,
		"supportTeams": [] if user.support_teams is None else user.support_teams.split(","),
		"peerNum": main_travel.peer_num,
		"labels": [] if user.labels is None or user.labels == "" else user.labels.split(","),
		"description": user.description,
		"id": main_travel.id,
		"fromCity": main_travel.from_city,
		"toCity": main_travel.to_city,
		"startDate": main_travel.start_date,
		"returnDate": main_travel.end_date,
		"matches": [] if main_travel.matches is None or main_travel.matches == "" else main_travel.matches.split(","),
		"vehicle": main_travel.vehicle,
		"vehicleNo": main_travel.vehicle_no,
		"travels": detail_travel_results,
		"is_date": is_date,
	}
